﻿using System;
using System.Data;
using System.Data.SqlClient;
using AutoUnitTestEngine.ValObjs;

namespace AutoUnitTestEngine.DbAccess
{
    public class BaseDataAccess
    {
        protected string ConnStr { get; set; }

        /// <summary>
        /// 向数据库获取数据
        /// </summary>
        /// <param name="sql">Sql查询语句</param>
        /// <returns>DataTable数据集体</returns>
        public DataTable GetDataTable(string sql)
        {
            var da = new SqlDataAdapter(sql, ConnStr);
            var reVal = new DataTable();
            try
            {
                da.Fill(reVal);
            }
            finally
            {
                da.Dispose();
            }
            return reVal;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="conditionString"></param>
        /// <returns></returns>
        public DataTable GetSingleDbTableData(string tableName, string conditionString)
        {
            return GetDataTable("Select * from " + tableName + " " + conditionString);
        }

        /// <summary>
        /// 在数据库中执行Sql脚本
        /// </summary>
        /// <param name="sql">Sql语句</param>
        public void ExecSql(string sql)
        {
            ExecSql(sql, true);
        }

        public void ExecSql(string sql, bool isTran)
        {
            var cn = new SqlConnection(ConnStr);
            var comm = new SqlCommand(sql, cn) {CommandTimeout = 900};
            cn.Open();
            if (isTran)
                comm.Transaction = cn.BeginTransaction();
            try
            {
                comm.ExecuteNonQuery();
                if (isTran)
                    comm.Transaction.Commit();
            }
            catch (Exception ex)
            {
                if (isTran)
                    comm.Transaction.Rollback();
                throw ex;
            }
            finally
            {
                comm.Dispose();
                cn.Close();
                cn.Dispose();
            }
        }

        /// <summary>
        /// 执行ValExecSql中的Sql
        /// </summary>
        /// <param name="valExecSql"></param>
        public void RunValSql(ValExecSql valExecSql)
        {
            if (valExecSql != null)
            {
                string strRunSql = valExecSql.GetRunSql();
                if (strRunSql.Length > 0)
                    ExecSql(strRunSql);
            }
        }
    }
}